package Test32;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;

//利用HashSet集合去除重复元素
/*
需求:创建一个存储学生对象的集合，存储多个学生对象。
使用程序实现在控制台遍历该集合。
要求:学生对象的成员变量值相同，我们就认为是同一个对象
 */
public class Test17 {
    public static void main(String[] args) {

        //1、创建一个set集合
        HashSet<Student17> s = new HashSet<>();

        //2、创建学生对象
        Student17 s1 = new Student17("zhangsan", 23);
        Student17 s2 = new Student17("zhangsan", 23);
        Student17 s3 = new Student17("lisi", 24);
        Student17 s4 = new Student17("wangwu", 25);
        Student17 s5 = new Student17("zhaoliu", 26);

        //3、添加数据
        System.out.println(s.add(s1));
        System.out.println(s.add(s2));
        System.out.println(s.add(s3));
        System.out.println(s.add(s4));
        System.out.println(s.add(s5));

        //4、遍历集合
        Iterator<Student17> it = s.iterator();
        while (it.hasNext()) {
            Student17 stu = it.next();
            System.out.println(stu.getName() + " " + stu.getAge());
        }
    }
}

class Student17 {
    private String name;
    private int age;


    public Student17() {
    }

    public Student17(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     *
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     *
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     *
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student17 student17 = (Student17) o;
        return age == student17.age && Objects.equals(name, student17.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    public String toString() {
        return "Student17{name = " + name + ", age = " + age + "}";
    }
}
